package com.shadow.demo.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shadow.demo.data.shiro.entity.Role;
import com.shadow.demo.data.shiro.entity.User;
import com.shadow.demo.data.shiro.entity.UserRole;
import com.shadow.demo.data.shiro.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserRoleService extends BaseService<UserRoleMapper, UserRole> implements IService<UserRole> {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Lazy
    @Resource
    private UserRoleService userRoleS;

    /**
     * 给指定角色分配权限
     * */
    public int configRole(final String userId, final List<String> role) {
        final User user = userService.getById(userId);
        List<Role> roleList = roleService.getByNameList(role);
        if (Objects.isNull(user) || CollectionUtils.isEmpty(roleList)) {
            return 0;
        }
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<UserRole>()
                .in(UserRole::getUserId, user.getId());
        remove(wrapper);
        wrapper.clear();
        List<UserRole> collect = roleList.stream()
                .map(x -> new UserRole(userId, x.getId()))
                .collect(Collectors.toList());
        userRoleS.saveBatch(collect);
        return collect.size();
    }
}
